<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="手机号" v-bind="validateInfos.phone">
	          <a-input-number v-model:value="formData.phone" placeholder="请输入手机号" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="姓名" v-bind="validateInfos.realname">
            <a-input v-model:value="formData.realname" placeholder="请输入姓名" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="!formData.id">
          <a-form-item label="登录密码" v-bind="validateInfos.password">
            <StrengthMeter v-model:value="formData.password" placeholder="请输入登录密码" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="!formData.id">
          <a-form-item label="确认密码" v-bind="validateInfos.confirmPassword">
            <a-input-password visibilityToggle v-model:value="formData.confirmPassword" placeholder="请输入确认密码" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="操作权限" v-bind="validateInfos.businessOptAuth">
            <j-dict-select-tag type="radio" placeholder="请选择操作权限" v-model:value="formData.businessOptAuth" stringToNumber="true" dictCode="caishui_b_opt_auth" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
import { computed, defineExpose, defineProps, nextTick, reactive, ref } from "vue";
import { useMessage } from "/@/hooks/web/useMessage";
import { getValueType } from "/@/utils";
import { saveOrUpdate } from "../CaishuiBusinessUser.api";
import { Form } from "ant-design-vue";
import { StrengthMeter } from "/@/components/StrengthMeter";
import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
import { duplicateValidate } from "/@/utils/helper/validator";

const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    businessId: '',
    userId: '',
    phone: undefined,
    realname: '',
    password: '',
    confirmPassword: '',
    businessOptAuth: 1,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    phone: [{ required: true, message: '请输入手机号!'},
      // { validator: phoneDuplicatevalidate },
      { pattern: /^1[3|4|5|7|8|9][0-9]\d{8}$/, message: '手机号码格式有误' }],
    realname: [{ required: true, message: '请输入姓名!'},],
    password: [{ validator: pswValidate}],
    confirmPassword: [{ validator: pswConfirmValidate}],
    businessOptAuth: [{ required: true, message: '请选择操作权限!'},],
  };
  const { resetFields, validate, validateInfos, clearValidate } = useForm(formData, validatorRules, { immediate: true });

   // 表单禁用
   const disabled = computed(()=>{
      let bool = false;
      if(props.formBpm === true){
        if(props.formData.disabled === false){
          bool = false;
        }else{
          bool =  true;
        }
      }
      bool = props.formDisabled;
      //清除表单验证
      clearValidate();
      return bool;
   });

  
  /**
   * 新增
   */
  function add(record) {
    edit(record);
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 手机号验证
   * @param _r
   * @param value
   */
  async function phoneDuplicatevalidate(_r, value) {
    return duplicateValidate('sys_user', 'username', value, formData.id || '')
  }

  /**
   * 登录密码验证
   * @param rule
   * @param value
   * @param callback
   */
  function pswValidate(rule, value, callback){
    if(!value && !formData.id){
      callback('请输入登录密码');
    }else {
      callback();
    }
  }

  /**
   * 确认密码验证
   * @param rule
   * @param value
   * @param callback
   */
  function pswConfirmValidate(rule, value, callback){
    if(!value && !formData.id){
      callback('请输入确认密码');
    }else if(value !== formData.password && !formData.id){
      callback('两次输入的密码不一致');
    }else {
      callback();
    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    if(!formData.businessId){
      createMessage.error("参数错误");
      return;
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //数据格式化
    let model = formData;
    if (model.id) {//编辑
       isUpdate.value = true;
       model.updateBy = "";
       model.updateTime = "";
    }else {//新增
       model.createBy = "";
       model.createTime = "";
       model.sysOrgCode = "";
       model.updateBy = "";
       model.updateTime = "";
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    console.log("表单提交参数:",model)
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
</style>
